import logging
import dashscope
import random
from dashscope import Generation
from http import HTTPStatus
from .. import AiAdapter, AiQuery, AiQueryResult
from common import canDirectAccessNet
import requests
import json


LOGGER = logging.getLogger(__name__)

_API_KEY = "xxxxxxxxxxxxxx"
_API_URL = "https://api.openai.com/v1/chat/completions"
_MODEL = "gpt-3.5-turbo-0125"


class Gpt35(AiAdapter):
    def query(self, query: AiQuery) -> AiQueryResult:
        LOGGER.info(query.userMessage)

        headers = {
            "Authorization": f"Bearer {_API_KEY}",
            "Content-Type": "application/json",
        }
        payload = {
            "model": _MODEL,
            "messages": [{"role": "user", "content": query.userMessage}],
        }

        LOGGER.info(f"发出请求：{query.userMessage}")
        try:
            requests.packages.urllib3.disable_warnings()
            r = requests.post(url=_API_URL, headers=headers, json=payload, verify=False)
            LOGGER.info(f"接口返回code:{r.status_code} body:{r.text}")
            if r.status_code == 200:
                jsonResponse = json.loads(r.text)

                return AiQueryResult(
                    text=jsonResponse["choices"][0]["message"]["content"],
                    totalToken=jsonResponse["usage"]["total_tokens"],
                )
            else:
                return AiQueryResult(isValid=False, errMessage=r.text)
        except Exception as e:
            LOGGER.exception(e)
            return AiQueryResult(isValid=False, errMessage=str(e))
